# -*- py-indent-offset: 4 -*- 
# -*- tab-width: 8 -*- 
# -*- indent-tabs-mode: nil -*-
from etgui import *
import CmdNo
from PageLayout import *
from ListEditor import TheListEditor
from types import StringType

############################################################################################
class ArrayEditor(TheListEditor):
	list_editor_dialog=None
	def __init__(self,model,path,title,sep=' ',sel=0):
		self.model=EditPotGuiModel(model)
		self.path=path
		self.title=title
		self.sep=sep
		self.sel=sel
		TheListEditor.__init__(self,title)
	def __call__(self):
		self.Show()
	def IsChangable(self,i):
		return self.changable
	# set all questions to Changable
	CanNew=CanEdit=CanRename=CanCopy=CanDelete = IsChangable
	def CanSwap(self,i,j):
		return self.changable
	def Show(self):
		self.changable=self.model.IsValueChangable(self.path)
		items=self.Split(self.model.GetValue(self.path))
		if items:
			self.SetItems(items)
		else:
			self.SetItems([])
		if not self.list_editor_dialog:
			view=MakeSectionLayout(MakeListEditorLayout(self))
			self.list_editor_dialog=MakeOkCancelDialog(self.title,self.model,view)
		if self.list_editor_dialog.ShowUnderMouse()==CmdNo.cIdOk:
			self.model.SetValue(self.path,self.Join(self.GetItems())) 
			self.model.Apply()
	def Split(self,value):
		if value is None:
			return []
		elif type(value) is StringType:
			result=[]
			for i in string.split(value,self.sep):
				if i:
					result.append(i)
			return result
		else:
			return value
	def Join(self,value):
		return value
	def ShowEditDialog(self,how,default):
		m=PotGuiModel()
		m.SetValue("Name",default)
		if self.sel==1:
			f=PotGuiDirSelector("Name",gTextFieldLen)
		elif self.sel==2:
			f=PotGuiFileSelector("Name",gTextFieldLen)
		elif self.sel==3:
			f=PotGuiDirFileSelector("Name",gTextFieldLen)
		else:
			f=PotTextField("Name")
		retval=ShowSubDialog("%s %s" %(how,self.what),
			m,
			f
		)
		if retval:
			return m.GetValue("Name")
		else:
			return None
class IncludeDirectivesEditor(ArrayEditor):
	def ShowEditDialog(self,how,default):
		m=PotGuiModel()
		m.SetValue("Name",default)
		def SelectDir(model=m):
			dirname=model.GetValue("Name")
			if dirname[:2] == '-I':
				dirname=dirname[2:]
			dirname=ShowDirDialog(dirname,"Secect an include directory")
			if dirname:
				model.SetValue("Name","-I"+dirname)
		dir_button=ActionButton("Dir...",action=SelectDir)
		f=FieldWithButtonLayout(PotTextField("Name"),dir_button)
		retval=ShowSubDialog("%s %s" %(how,self.what),
			m,
			f
		)
		if retval:
			return m.GetValue("Name")
		else:
			return None
		pass
class GeneralListEditor(ArrayEditor):
	def Join(self,list):
		# join list into a string
		if list:
			return string.join(list,self.sep)
		else:
			return ""
